package com.wtcrazy.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/*
 * 跨域配置
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 一小时内不需要再预检
        registry.addMapping("/**")//可以被跨域的路径
                .allowedOrigins("*")//允许所有的请求
                .allowCredentials(true)
                .allowedHeaders(CorsConfiguration.ALL)//允许所有的请求访问头部
                .allowedMethods(CorsConfiguration.ALL)//允许请求的方法
                .maxAge(3600);//缓存时间【1h】
    }

    /**
     * 跨域配置后swagger2可能不能访问，需要增加如下配置
     * @param registry 对静态资源的配置
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
